<template>
  <el-container class="container">
    <el-header height="100%">
      <el-form :model="menuForm" ref="menuForm" label-width="80px" class="form">
        <el-row>
          <el-col :span="6">
            <el-form-item label="菜单名称" prop="menuName">
              <el-input v-model="menuForm.menuName" clearable placeholder="请输入菜单名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜单状态" prop="status">
              <el-select v-model="menuForm.status" clearable placeholder="请选择状态">
                <el-option label="正常" value="true"/>
                <el-option label="停用" value="false"/>
              </el-select>
              <div style="display: inline; margin-left: 10px">
                <el-button type="primary" @click="onSubmit" icon="el-icon-search">搜索</el-button>
                <el-button @click="resetForm('menuForm')" icon="el-icon-refresh">重置</el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="padding-left: 10px">
          <el-button type="primary" plain icon="el-icon-plus" @click="showAddDialog()">新增</el-button>
          <el-button type="info" plain icon="el-icon-sort" @click="toggleExpandAll">展开/折叠</el-button>
        </el-row>
      </el-form>
    </el-header>
    <el-main>
      <el-table
        v-if="refreshTable"
        :data="menuData"
        style="width: 100%"
        row-key="menuId"
        :tree-props="{children: 'children'}"
        :header-cell-style="{'text-align':'center'}"
        :default-expand-all="isExpandAll">
        <el-table-column
          align="left"
          prop="menuName"
          label="菜单名称"
          min-width="180">
        </el-table-column>
        <el-table-column
          prop="icon"
          label="图标"
          align="center"
          min-width="60">
          <template slot-scope="scope">
            <svg-icon :icon-class="scope.row.icon"/>
          </template>
        </el-table-column>
        <el-table-column
          prop="orderNum"
          label="排序"
          align="center"
          min-width="60">
        </el-table-column>
        <el-table-column
          prop="perms"
          label="权限标识"
          align="center"
          min-width="120">
        </el-table-column>
        <el-table-column
          prop="component"
          label="组件路径"
          align="center"
          min-width="120">
        </el-table-column>
        <el-table-column
          prop="visible"
          align="center"
          label="状态"
          min-width="120">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.visible === true">正常</el-tag>
            <el-tag v-else type="danger">停用</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="createTime"
          align="center"
          label="创建时间"
          min-width="160">
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          align="center"
          min-width="180">
          <template slot-scope="scope">
            <el-row>
              <el-button type="text" icon="el-icon-edit" size="small" @click="showEditDialog(scope.row)">修改
              </el-button>
              <el-button type="text" icon="el-icon-plus" size="small" @click="showAddDialog(scope.row.menuId)">新增
              </el-button>
              <el-button type="text" icon="el-icon-delete" size="small" @click="handlerRemove(scope.row.menuId)">删除
              </el-button>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
    </el-main>
    <el-dialog :title="menuDialog.title" width="600px" :visible.sync="menuDialog.visible">
      <el-form :model="menuDialog.form" :rules="menuDialog.rules" ref="menuDialogForm">
        <el-row>
          <el-col :span="24">
            <el-form-item label="上级菜单" :label-width="menuDialog.formLabelWidth" prop="parentId">
              <el-select v-model="menuDialog.form.parentId" clearable @clear="clearParentMenu" placeholder="请选择">
                <template v-slot:prefix v-if="menuDialog.other.parentIcon !== ''">
                  <svg-icon :icon-class="menuDialog.other.parentIcon" style="margin-left: 5px"></svg-icon>
                </template>
                <el-option :value="menuDialog.form.parentId" :label="menuDialog.other.parentName"
                           style="height: 100%;padding: 0">
                  <el-tree
                    :data="menuDialogOptions"
                    :props="{label: 'menuName',value: 'menuId'}"
                    accordion
                    @node-click="handleNodeClick">
                    <span class="custom-tree-node" slot-scope="{ node, data }">
                      <svg-icon :icon-class="data.icon"/>&nbsp;
                      <span>{{ data.menuName }}</span><span v-if="data.children != null && data.children.length > 0">&nbsp;({{
                        data.children.length
                      }})</span>
                    </span>
                  </el-tree>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="菜单类型" :label-width="menuDialog.formLabelWidth" prop="menuType">
              <el-radio-group v-model="menuDialog.form.menuType">
                <el-radio label="M">目录</el-radio>
                <el-radio label="C">菜单</el-radio>
                <el-radio label="F">按钮</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="菜单名称" :label-width="menuDialog.formLabelWidth" prop="menuName">
              <el-input v-model="menuDialog.form.menuName" autocomplete="off" placeholder="请输入菜单名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="menuDialog.form.menuType !== 'F'">
            <el-form-item label="菜单图标" :label-width="menuDialog.formLabelWidth" prop="icon">
              <el-autocomplete
                class="inline-input"
                v-model="menuDialog.form.icon"
                :fetch-suggestions="querySearch"
                placeholder="请选择菜单图标"
                clearable
                placement="top-end"
                @select="handleSelect"
              >
                <template v-slot:prepend>
                  <svg-icon :icon-class="menuDialog.form.icon"></svg-icon>
                </template>
                <template slot-scope="{ item }">
                  <svg-icon :icon-class="item"></svg-icon>&nbsp;
                  <span>{{ item }}</span>
                </template>
              </el-autocomplete>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" :label-width="menuDialog.formLabelWidth" prop="orderNum">
              <el-input-number v-model="menuDialog.form.orderNum" placeholder="请选择顺序" controls-position="right"
                               :min="1"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="menuDialog.form.menuType !== 'F'">
            <el-form-item label="是否外链" :label-width="menuDialog.formLabelWidth" prop="isLink">
              <el-radio-group v-model="menuDialog.form.isIframe">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="menuDialog.form.menuType !== 'F'">
            <el-form-item label="路由地址" :label-width="menuDialog.formLabelWidth" prop="path">
              <el-input v-model="menuDialog.form.path" autocomplete="off" placeholder="请输入路由地址"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="menuDialog.form.menuType === 'C'">
            <el-form-item label="组件路径" :label-width="menuDialog.formLabelWidth" prop="component">
              <el-input v-model="menuDialog.form.component" autocomplete="off" placeholder="请输入组件路径"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="menuDialog.form.menuType !== 'M'">
            <el-form-item label="权限字符" :label-width="menuDialog.formLabelWidth" prop="perms">
              <el-input v-model="menuDialog.form.perms" autocomplete="off" placeholder="请输入权限字符标识"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="menuDialog.form.menuType === 'C'">
            <el-form-item label="路由参数" :label-width="menuDialog.formLabelWidth" prop="query">
              <el-input v-model="menuDialog.form.query" autocomplete="off" placeholder="请输入路由参数"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="menuDialog.form.menuType !== 'F'">
            <el-form-item label="显示状态" :label-width="menuDialog.formLabelWidth" prop="visible">
              <el-radio-group v-model="menuDialog.form.hidden">
                <el-radio :label="true">显示</el-radio>
                <el-radio :label="false">隐藏</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="menuDialog.form.menuType !== 'F'">
            <el-form-item label="菜单状态" :label-width="menuDialog.formLabelWidth" prop="visible">
              <el-radio-group v-model="menuDialog.form.visible">
                <el-radio :label="true">正常</el-radio>
                <el-radio :label="false">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="menuDialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="submitDialog">确 定</el-button>
      </div>
    </el-dialog>

  </el-container>
</template>

<script>
import menuApi from '@/api/system/menu';
import icons from '@/components/IconSelect/requireIcons';
import {dynamicRouter, resetRouter} from '@/router';
import SvgIcon from '@/components/SvgIcon';

export default {
  name: 'index',
  data() {
    return {
      menuForm: {
        menuName: '',
        status: null,
      },
      iconList: icons,
      menuData: [],
      refreshTable: true,
      isExpandAll: false,
      menuDialogOptions: [],
      menuDialog: {
        visible: false,
        title: '添加菜单',
        other: {
          parentName: '主类目',
          parentIcon: '',
        },
        form: {
          parentId: 0,
          menuType: 'M',
          icon: '',
          level: 0,
          menuName: '',
          component: '',
          perms: '',
          query: '',
          orderNum: '',
          isIframe: false,
          path: '',
          visible: true,
          hidden: true,
        },
        formLabelWidth: '80px',
      },
    };
  },
  components: {
    SvgIcon,
  },
  created() {
    this.fetchData();
    this.getParentMenuTree();
  },
  methods: {
    fetchData() {
      menuApi.getMenuTree(this.menuForm).then(res => {
        this.menuData = res.data;
      });
    },
    getParentMenuTree() {
      menuApi.getMenuTree(this.menuForm).then(res => {
        const body = {
          'parentId': 0,
          'menuId': 0,
          'level': 0,
          'menuName': '主类目',
          'children': res.data,
          'icon': '',
        };
        this.menuDialogOptions = [body];
      });
    },
    handleNodeClick(data) {
      console.log('点击菜单:', data);
      this.menuDialog.form.parentId = data.menuId;
      this.menuDialog.other.parentName = data.menuName;
      this.menuDialog.other.parentIcon = data.icon;
      this.menuDialog.form.level = data.level;
    },
    handleChangeParentMenu(value) {
      this.menuDialog.form.parentId = value;
    },
    showAddDialog(parentId) {
      this.menuDialog.form = this.$options.data().menuDialog.form;
      this.menuDialog.other = this.$options.data().menuDialog.other;
      this.getParentMenuTree();
      if (!!parentId) {
        let parent = this.filterParent(parentId);
        this.menuDialog.other.parentName = parent.menuName;
        this.menuDialog.other.parentIcon = parent.icon;
        this.menuDialog.form.level = parent.level;
        this.menuDialog.form.parentId = parentId;
      }
      this.menuDialog.title = '添加菜单';
      this.menuDialog.visible = true;
    },
    querySearch(queryString, cb) {
      let iconList = icons;
      let results = queryString
        ? iconList.filter(icon => icon.toLowerCase().includes(queryString.toLowerCase()))
        : iconList;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    handleSelect(item) {
      this.menuDialog.form.icon = item;
    },
    clearParentMenu() {
      this.menuDialog.other.parentName = '主类目';
      this.menuDialog.other.parentIcon = '';
      this.menuDialog.form.parentId = 0;
      this.menuDialog.form.level = 0;
    },
    filterParent(parentId, arr = this.menuDialogOptions) {
      for (const menuDialogOption of arr) {
        if (menuDialogOption.menuId === parentId) {
          return menuDialogOption;
        } else if (menuDialogOption.children && menuDialogOption.children.length) {
          let option = this.filterParent(parentId, menuDialogOption.children);
          if (option) {
            return option;
          }
        }
      }
      return null;
    },
    showEditDialog(row) {
      this.menuDialog.form = this.$options.data().menuDialog.form;
      this.menuDialog.other = this.$options.data().menuDialog.other;
      menuApi.getById(row.menuId).then(res => {
        this.menuDialog.form = res.data;
        this.menuDialog.form.level = res.data.level - 1;
      });
      this.getParentMenuTree();
      let parent = this.filterParent(row.parentId);
      this.menuDialog.other.parentName = parent.menuName;
      this.menuDialog.other.parentIcon = parent.icon;
      this.menuDialog.title = '修改菜单';
      this.menuDialog.visible = true;
      console.log(this.menuDialog.form);
    },
    submitDialog() {
      // 校验
      this.updateMenu(this.menuDialog.title);
    },
    updateMenu(msg) {
      this.$confirm('确定要' + msg + '吗?', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.menuDialog.form.level++;
        console.log(this.menuDialog.form);
        menuApi.updateMenu(this.menuDialog.form).then(() => {
          this.menuDialog.visible = false;
          this.fetchData();
          this.$message({
            type: 'success',
            message: msg + '成功',
          });
        });
      });
    },
    onSubmit() {
      this.fetchData(1);
    },
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    resetForm(formName) {
      if (this.$refs[formName] !== undefined) {
        this.$refs[formName].resetFields();
        this.fetchData(1);
      }
    },
    handlerRemove(menuId) {
      this.$confirm('确定要删除吗?', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        menuApi.delById(menuId).then(() => {
          this.fetchData(1);
          this.$message({
            message: '删除成功',
            type: 'success',
          });
        });
      });
    },
  },
};
</script>

<style scoped>
.line {
  text-align: center;
}

.form {
  /*padding-top: 20px;*/
  /*padding-bottom: -15px;*/
}

.container {
  padding: 20px 10px;
}
</style>
